package com.zhuoyue.common.mqtt.util;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @ClassName: WSMQTTServerCallBack
 * @Description:
 * @author wjming
 * @Date 2021-07-08 16:27
 */
public class WsMqttServerCallBack implements MqttCallback {

	private String instanceData = "";

	public WsMqttServerCallBack(String instance){
		instanceData = instance;
	}

	/**
	 * 接收到消息之后的回调方法
	 */
	@Override
	public void messageArrived(String topic , MqttMessage message){
		try{
			System.out.println("Message arrived: \"" + message.toString()
		              + "\" on topic \"" + topic.toString() + "\" for instance \""
		              + instanceData + "\"");

		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 消息连接丢失
	 */
	@Override
	public void connectionLost(Throwable cause){
		System.out.println("Connection lost on instance \"" + instanceData
	            + "\" with cause \"" + cause.getMessage() + "\" Reason code "
	            + ((MqttException)cause).getReasonCode() + "\" Cause \""
	            + ((MqttException)cause).getCause() +  "\"");
	        cause.printStackTrace();
	}

	/**
	 * 所有消息传送完成之后调用
	 */
	@Override
	public void deliveryComplete(IMqttDeliveryToken token){
		try{
			System.out.println("Delivery token \"" + token.hashCode()
		              + "\" received by instance \"" + instanceData + "\"");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



}
